package com.hulman.oms.web;

import com.hulman.oms.bean.Fault;
import com.hulman.oms.bean.Result;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.service.FaultService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
@Slf4j
public class FaultController
{
    private static final String MODEL = "qwen2.5vl:32b";

    @Value("${img-home}")
    private String imgHome;
    @Autowired
    private FaultService faultService;
    @Autowired
    private OllamaChatModel ollamaChatModel;

    /**
     * 视觉识别缺陷
     *
     * @return
     */
    @PostMapping("/faults/recognize")
    public Result recognize(String images) throws Exception
    {
        if (StringUtil.isEmpty(images))
        {
            throw new IoTException("请先上传图片");
        }
        String prompt = "简要描述图片中存在的问题，不超过20个字";
        String[] imageList = images.split(",");
        List<Media> mediaList = new ArrayList<>();
        for (String image : imageList)
        {
            String imgPath = imgHome + image;
            Resource resource = new PathResource(Paths.get(imgPath));
            mediaList.add(new Media(MimeTypeUtils.IMAGE_JPEG, resource));
        }
        UserMessage userMessage = UserMessage.builder().text(prompt).media(mediaList).build();
        // 调用多模态模型
        ChatResponse response = ollamaChatModel.call(new Prompt(userMessage, OllamaOptions.builder().model(MODEL).build()));
        String data = response.getResult().getOutput().getText();
        return new Result(data);
    }

    @GetMapping("/faults/{id}")
    public Result findFaultById(@PathVariable Integer id)
    {
        Fault fault = faultService.findFaultById(id);
        return new Result(fault);
    }

    @GetMapping("/faults")
    public Result findFaults(Integer page, Integer limit, Integer deviceId, Integer source, String no, String content, String reportByName, Integer auditTimes, Integer state)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("deviceId", deviceId);
        map.put("source", source);
        map.put("no", no);
        map.put("content", content);
        map.put("reportByName", reportByName);
        map.put("auditTimes", auditTimes);
        map.put("state", state);
        return faultService.findFaultsResult(map);
    }

    @DeleteMapping("/faults/{ids}")
    public Result deleteFaultById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            faultService.deleteFaultById(id);
        }
        return Result.SUCCESS;
    }

    /**
     * 上报缺陷
     *
     * @param content
     * @param deviceId
     * @param deviceName
     * @param faultHandle
     * @param faultImgs
     * @return
     */
    @PostMapping("/faults/report")
    public Result report(Integer source, Integer alarmId, String content, Integer deviceId, String deviceName, String deviceLocation, Integer teamId, Integer faultHandle, String faultImgs)
    {
        faultService.report(source, alarmId, content, deviceId, deviceName, deviceLocation, teamId, faultHandle, faultImgs);
        return Result.SUCCESS;
    }

    /**
     * 维修处置
     *
     * @param id
     * @param level
     * @param repairHandle
     * @return
     */
    @PostMapping("/faults/repair")
    public Result repair(Integer taskId, Integer id, Integer level, Integer repairHandle)
    {
        faultService.repair(taskId, id, level, repairHandle);
        return Result.SUCCESS;
    }

    /**
     * 审核缺陷
     *
     * @param taskId
     * @param id
     * @param auditResult
     * @param auditComment
     * @param auditLocation
     * @param auditImgs
     * @return
     */
    @PostMapping("/faults/audit")
    public Result audit(Integer taskId, Integer id, Integer level, Integer auditResult, String auditComment, String auditLocation, String auditImgs)
    {
        faultService.audit(taskId, id, level, auditResult, auditComment, auditLocation, auditImgs);
        return Result.SUCCESS;
    }

    /**
     * 撤销缺陷
     *
     * @param id
     * @return
     */
    @PostMapping("/faults/terminate")
    public Result terminate(Integer id)
    {
        faultService.terminate(id);
        return Result.SUCCESS;
    }

}
